/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.handlers;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.zfes.snowy.auth.AuthConsts;
import org.zfes.snowy.core.data.JSONMSG;
import org.zfes.snowy.core.util.UUIDUtil;
import org.zfes.snowy.core.util.ZWebUtil;

public class SimpleAuthecSuccessHandler extends AbstractAuthecHandler{

    private String defaultAuthecSuccessUrl="/index.html";
    
    private boolean authecSuccessForwardToDestination = false;
    
	@Override   
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,Subject subject,boolean isGenCSRFToken) throws IOException, ServletException {
		if(ZWebUtil.isAjax(request)){
			JSONMSG jsonmsg=JSONMSG.newMSG(200,"认证成功").put("subject", subject.getPrincipal());
			if(isGenCSRFToken) {
				String csrfToken=UUIDUtil.base58Uuid();
				jsonmsg.put(AuthConsts.HEADER.CSRF_TOKEN, UUIDUtil.base58Uuid());
				subject.getSession().setAttribute(AuthConsts.SESSION.SESSION_CSRF_TOKEN, csrfToken);
			}
			ZWebUtil.respJSON(response,jsonmsg);
		}else{
			String successUrl=defaultAuthecSuccessUrl;
			SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
			 if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
		            successUrl = savedRequest.getRequestUrl();
		        }
			if(authecSuccessForwardToDestination){
				ZWebUtil.forward(request, response, successUrl);
				return;
			}else{
				WebUtils.redirectToSavedRequest(request, response, successUrl);
				//saveRequestAndRedirect( request,  response, getDefaultAuthecSuccessUrl());
				return;
			}
		}
	}

	public String getDefaultAuthecSuccessUrl() {
		return defaultAuthecSuccessUrl;
	}

	public void setDefaultAuthecSuccessUrl(String defaultAuthecSuccessUrl) {
		this.defaultAuthecSuccessUrl = defaultAuthecSuccessUrl;
	}

	public boolean isAuthecSuccessForwardToDestination() {
		return authecSuccessForwardToDestination;
	}

	public void setAuthecSuccessForwardToDestination(boolean authecSuccessForwardToDestination) {
		this.authecSuccessForwardToDestination = authecSuccessForwardToDestination;
	}

}